#include "head.h"

int trans_exit = 0;//退出标记位,1表示有退出信号
void func(int num){
    trans_exit = 1;
}
//用户下载，接收服务端发来的文件
int recv_file(const char *file_name, int socket_fd){
    int fd = open(file_name, O_RDWR | O_CREAT, 0666);
    //获取偏移量
    struct stat stat_file;
    fstat(fd, &stat_file);
    off_t offset = stat_file.st_size;

    //向服务端发送偏移量
    send(socket_fd, &offset, sizeof(off_t), MSG_NOSIGNAL);

    //接收文件大小
    off_t file_size;
    recv(socket_fd, &file_size, sizeof(off_t), MSG_WAITALL);

    printf("offset=%ld\n", offset);

    printf("filesize=%ld\n", file_size);


    ftruncate(fd, file_size);

    char *p = (char *)mmap(NULL, file_size, PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
    char *curr = p + offset;

    signal(2, func);

    //接收文件
    int recv_count = recv(socket_fd, curr, file_size - offset, MSG_WAITALL);
    offset += recv_count;
    if(trans_exit == 1){
        //有退出信号
        munmap(p, file_size);
        ftruncate(fd, offset);
    }

    munmap(p, file_size);
    ftruncate(fd, offset);

    signal(2, SIG_DFL);
    close(fd);
    return 0;
}


//用户上传，向服务器发送文件
int send_file(const char *file_name, int socket_fd){
    int fd = open(file_name, O_RDWR);
    if(fd == -1){
        printf("file does not exists\n");
        return -1;
    }

    //获取文件大小
    struct stat stat_file;
    fstat(fd, &stat_file);
    off_t file_size = stat_file.st_size;

    //发送文件大小
    send(socket_fd, &file_size, sizeof(off_t), MSG_NOSIGNAL);

    //接收起始偏移量
    off_t offset;
    recv(socket_fd, &offset, sizeof(off_t), MSG_WAITALL);

    //发送文件
    sendfile(socket_fd, fd, &offset, file_size - offset);

    close(fd);
    return 0;
}
